<template>
  <span class="flow-button-warp">
    <template v-if="type !== 'view'">
      <fks-button
        v-for="(item, index) in buttonList"
        :key="index"
        :plain="item.type !== 'submit'"
        :type="buttonType(item)"
        :loading="loading"
        @click="clickHandler(item)"
      >
        <svg-icon
          v-if="!loading"
          style="margin-right: 6px; vertical-align: middle"
          :icon-class="buttonIcon(item)"
          class-name
        ></svg-icon>
        <span style="display: inline-block; vertical-align: middle">{{
          LANG[item.customCode || item.code] || item.text
        }}</span>
      </fks-button>
    </template>
    <fks-button
      v-if="!isFakeCustom && type !== 'add'"
      @click="setFlowCanvasVisible"
      :loading="loading"
      icon="fks-icon-view"
    >
      <span style="display: inline-block; vertical-align: middle">
        查看流程
      </span>
    </fks-button>
    <fks-dialog
      title="选择抄送人"
      @open="open"
      append-to-body
      :visible.sync="circulationInfo.visible"
      @close="cancel()"
    >
      <fks-form>
        <fks-form-item label="抄送人">
          <fks-user-selector
            style="width: 100%"
            url
            multiple
            :username.sync="circulationInfo.userName"
            :userfullname.sync="circulationInfo.userFullName"
          ></fks-user-selector>
        </fks-form-item>
        <fks-form-item label="抄送人通知方式">
          <fks-checkbox-group v-model="notifyMethods">
            <fks-checkbox
              v-for="item in notifyMethodOptions"
              :label="item.value"
              :key="item.value"
              >{{ item.label }}</fks-checkbox
            >
          </fks-checkbox-group>
        </fks-form-item>
      </fks-form>
      <span slot="footer" class="dialog-footer">
        <fks-button @click="cancel">取 消</fks-button>
        <fks-button type="primary" @click="circulationInfoHandler"
          >确 定</fks-button
        >
      </span>
    </fks-dialog>
    <fks-dialog
      title="选择退回节点"
      :visible.sync="innerRejectVisible"
      @close="cancelReject()"
      append-to-body
    >
      <fks-select v-model="rejectTaskKey" placeholder="请选择退回节点">
        <fks-option
          v-for="item in rejectNodeOptions"
          :key="item.taskKey"
          :label="item.taskName"
          :value="item.taskKey"
        >
        </fks-option>
      </fks-select>
      <div slot="footer" class="dialog-footer">
        <fks-button @click="cancelReject()">取 消</fks-button>
        <fks-button type="primary" @click="confirmReject(rejectTaskKey)"
          >确 定</fks-button
        >
      </div>
    </fks-dialog>
  </span>
</template>
<script>
import Mix from '@/mixins/module'
import eventBus from '../FlowButton/eventBus'
// import downloadPdf from '@/utils/htmlToPdf'
import {
  processAbandon,
  // processStart,
  // processComplete,
  // processMulti,
  processReject,
  processButton,
  processTaskKey,
  // saveCustomNodeDetail,
  circulation
  // getCustomNodeDetail
} from './api'
export default {
  name: 'flowButton',
  mixins: [Mix],
  data() {
    return {
      circulationInfo: {
        visible: false, // 选择退回节点对话框
        userName: '',
        userFullName: ''
      },
      notifyMethods: [],
      notifyMethodOptions: [
        {
          label: '站内信',
          value: '0'
        },
        {
          label: '短信',
          value: '1'
        },
        {
          label: '邮件',
          value: '2'
        }
      ],
      buttonList: [],
      innerRejectVisible: false,
      rejectNodeOptions: [],
      rejectTaskKey: '',
      loading: false,
      type: this.$route.params.type,
      isFakeCustom: '',
      taskId: this.$route.params.taskId || '',
      taskKey: this.$route.params.taskKey || '',
      formKey: this.$route.params.formKey,
      bizId: this.$route.params.bizId,
      processInstanceId: this.$route.query.processInstanceId
    }
  },
  methods: {
    // //打印PDF
    // getPdf() {
    //    this.loading = true

    //   let dom = this.parentComponent.$refs.dialog.$el.getElementsByClassName(
    //     'fks-dialog__body'
    //   )[0]
    //   let title = this.formName
    //   downloadPdf(dom, title).then(() => {
    //      this.loading = false
    //   })
    // },
    buttonType(item) {
      switch (item.type) {
        case 'submit':
          return 'primary'
        default:
          return ''
      }
    },
    buttonIcon(item) {
      switch (item.type) {
        case 'abandon':
          return 'delete_4'
        case 'reject':
          return 'reject'
        case 'submit':
          return 'success_2'
        case 'saveDraft':
          return 'hold'
        case 'addCountersignee':
          return 'addto_1'
        case 'edit':
          return 'edit'
        case 'circulate':
          return 'circulate'
        default:
          return ''
      }
    },
    sortIcon(item) {
      switch (item.type) {
        case 'submit':
          return 1
        case 'saveDraft':
          return 2
        case 'reject':
          return 3
        case 'abandon':
          return 4
        case 'addCountersignee':
          return 5
        case 'edit':
          return 6
        case 'circulate':
          return 7
        default:
          return 8
      }
    },

    cancelReject() {
      this.innerRejectVisible = false
    },
    /**
     * @description: 驳回到指定节点
     * @param {taskId} 任务id
     * @param {comment} 评论
     * @param {targetKey} 指定节点
     */
    confirmReject(targetKey) {
      let flowData = {
        taskId: this.taskId,
        bizId: this.bizId,
        comment: this.comment,
        targetKey: targetKey
      }
      this.loading = true
      processReject(flowData)
        .then((res) => {
          if (res.status) {
            this.innerRejectVisible = false
            this.onOptSuccess(res, 'REJECT')
          }
        })
        .catch((err) => {
          this.catchHandler(err)
        })
      // this.onOptSuccess(res)
    },
    /**
     * @description: 按钮点击事件
     * @param {type} 按钮触发的方法类型
     */
    clickHandler(buttonInfo) {
      if (buttonInfo.type === 'reject') {
        processTaskKey({ taskId: this.taskId }).then((res) => {
          if (!res.status) {
            return
          }
          let rejectNodeOptions = res.data

          let index = rejectNodeOptions.findIndex((item) => {
            return item.taskKey === this.taskKey
          })
          rejectNodeOptions = rejectNodeOptions.filter((item, i) => {
            return i < index
          })
          if (rejectNodeOptions.length === 1) {
            this.confirmReject(rejectNodeOptions[0].taskKey)
          } else {
            this.rejectNodeOptions = rejectNodeOptions
            this.innerRejectVisible = true
          }
        })
      } else if (buttonInfo.type == 'circulate') {
        this.circulate(buttonInfo)
      } else {
        this.$confirm(
          '确认' +
            (this.LANG[buttonInfo.customCode || buttonInfo.code] ||
              buttonInfo.text) +
            '？',
          this.LANG.TIPS,
          {
            confirmButtonText: this.LANG.CONFIRM,
            cancelButtonText: this.LANG.CANCEL,
            type: 'warning'
          }
        )
          .then(() => {
            this[buttonInfo.type](buttonInfo)
          })
          .catch(() => {
            // 提交确认界面点击取消以后
            // this.$message({
            //   type: 'info',
            //   message: this.LANG.CANCEL
            // })
          })
      }
    },
    /**
     * @description: 完成操作成功之后的回调
     */
    // onOptSuccess() {
    //   this.$emit('on-success')
    // },
    getButton() {
      if (this.taskId) {
        processButton(this.taskId).then((res) => {
          const tempButtonList = JSON.parse(res.data.buttonList)
          if (
            tempButtonList.taskButtonList &&
            tempButtonList.taskButtonList.length
          ) {
            this.buttonList = tempButtonList.taskButtonList.sort(
              (a, b) => this.sortIcon(b) - this.sortIcon(a)
            )
          } else {
            this.buttonList = tempButtonList.sort(
              (a, b) => this.sortIcon(b) - this.sortIcon(a)
            )
          }
        })
      }
    },
    /**
     * @description: 提交请求
     */
    submit() {
      //通知eventBus,到"@/FormCenter/componentsWp/Form/index.vue中去执行""
      eventBus.$emit('submit')
    },
    /**
     * @description: 暂存
     */
    saveDraft() {
      eventBus.$emit('saveDraft')
    },
    /**
     * @description: 废弃
     */
    abandon() {
      let flowData = {
        taskId: this.taskId,
        bizId: this.bizId,
        formKey: this.formKey
      }
      processAbandon(flowData)
        .then((res) => {
          this.onOptSuccess(res, 'ABANDON')
        })
        .catch((err) => {
          this.catchHandler(err)
        })
    },
    open() {
      this.circulationInfo.userName = ''
      this.circulationInfo.userFullName = ''
      this.notifyMethods = []
    },
    cancel() {
      this.circulationInfo.visible = false
    },
    /**
     * @description: 抄送
     */
    circulate(buttonInfo) {
      this.circulationInfo.visible = true
    },
    circulationInfoHandler() {
      if (
        this.circulationInfo.userName &&
        this.circulationInfo.userName.length
      ) {
        this.loading = true
        circulation({
          formBizId: this.bizId,
          formKey: this.formKey,
          processInstanceId: this.processInstanceId,
          processType: 2,
          receiverUserName: this.circulationInfo.userName,
          receiverUserFullName: this.circulationInfo.userFullName,
          notify: JSON.stringify(this.notifyMethods),
          senderUserFullName: this.$store.state.user.userFullname,
          senderUserName: this.$store.state.user.userName,
          taskId: this.taskId,
          title: this.formName || '',
          sourceId: this.$store.state.portal.id || '',
          sourceName: this.$store.state.portal.name || ''
        }).then((res) => {
          this.receiverUserName = ''
          this.$message({
            type: 'success',
            message: '抄送成功',
            showClose: true
          })
          this.circulationInfo.visible = false
          this.loading = false
        })
      } else {
        this.$message({
          type: 'error',
          message: '无抄送人',
          showClose: true
        })
      }
    },
    onOptSuccess(data, type) {
      this.loading = false
      eventBus.$emit('success', type)
    },
    /**
     * @description:
     * @param {type}
     * @return:
     */
    catchHandler(error) {
      console.log(error)
      this.loading = false
      this.$emit('onCatch', error)
    },
    setFlowCanvasVisible() {
      eventBus.$emit('setFlowCanvasVisible', true)
    }
  },
  created() {
    eventBus.$on('setIsFakeCustom', (val) => {
      this.isFakeCustom = val
    })
    eventBus.$on('setLoading', (val) => {
      this.loading = val
    })
  },
  mounted() {
    if (this.taskId && this.type === 'execute') {
      this.getButton()
    } else if (this.type && this.type === 'add') {
      this.buttonList = [
        {
          type: 'saveDraft',
          text: '暂存',
          code: 'SAVEDRAFT',
          customCode: 'SAVEDRAFT'
        },
        {
          type: 'submit',
          text: '提交',
          code: 'SUBMIT',
          customCode: 'SUBMIT'
        }
      ]
    } else if (this.type && this.type === 'edit') {
      this.buttonList = [
        {
          type: 'submit',
          text: '修改',
          code: 'EDIT',
          customCode: 'SUBMIT'
        }
      ]
    }
  },
  beforeDestroy() {
    eventBus.$off('setIsFakeCustom')
    eventBus.$off('setLoading')
  }
}
</script>
<style lang="scss" scoped>
.flow-button-warp {
  ::v-deep .flow-button-inner {
    // display: inline-block;
    align-items: center;
  }
  .fks-steps {
    .fks-step {
      cursor: pointer;
    }
    .fks-step.active {
      .fks-step__main {
        color: #4ccae3 !important;
      }
      .fks-step__title {
        color: #4ccae3 !important;
      }
      .fks-step__description {
        color: #4ccae3 !important;
      }
      .fks-step__icon {
        color: #4ccae3 !important;
        border-color: #4ccae3 !important;
      }
    }
  }
}
</style>
